﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace Koonsoft.HYCRM.DAL
{
    public class DelegateRoleDAL
    {
        private Database database = DatabaseFactory.CreateDatabase("KOONCRMDB");

        /// <summary>
        /// 清理指定角色和业务的逻辑
        /// </summary>
        /// <param name="roleID"></param>
        /// <param name="deliverType"></param>
        public void RemoveDelegatesByRole(int roleID, int deliverType)
        {
            const string sql = "delete from DelegateRole where roleID=@roleID and deliverType=@deliverType";

            using (var cmd = database.GetSqlStringCommand(sql))
            {
                database.AddInParameter(cmd, "@roleID", DbType.Int32, roleID);
                database.AddInParameter(cmd, "@deliverType", DbType.Int32, deliverType);

                database.ExecuteNonQuery(cmd);
            }
        }

        /// <summary>
        /// 新增业务逻辑和角色的关系
        /// </summary>
        /// <param name="delegateType"></param>
        /// <param name="roleID"></param>
        /// <param name="deliverType"></param>
        public void AddDelegateWithRole(int delegateType, int roleID, int deliverType)
        {
            const string sql = "insert into DelegateRole values (@delegateType,@roleID,@deliverType)";

            using (var cmd = database.GetSqlStringCommand(sql))
            {
                database.AddInParameter(cmd, "@delegateType", DbType.Int32, delegateType);
                database.AddInParameter(cmd, "@roleID", DbType.Int32, roleID);
                database.AddInParameter(cmd, "@deliverType", DbType.Int32, deliverType);

                database.ExecuteNonQuery(cmd);
            }
        }

        /// <summary>
        /// 根据权限获取业务类型
        /// </summary>
        /// <param name="roleID"></param>
        /// <param name="deliverType"></param>
        /// <returns></returns>
        public List<int> GetDelegatesByRoleID(int roleID, int deliverType)
        {
            var delegates = new List<int>();

            const string procedure = "Delegate_GetDelegatesByRoleID";

            using (var cmd = database.GetStoredProcCommand(procedure))
            {
                database.AddInParameter(cmd, "@deliverType", DbType.Int32, deliverType);
                database.AddInParameter(cmd, "@roleID", DbType.Int32, roleID);

                var rd = (RefCountingDataReader)database.ExecuteReader(cmd);
                var sqlrd = (SqlDataReader)rd.InnerReader;

                while (sqlrd.Read())
                {
                    delegates.Add(Convert.ToInt32(sqlrd["DelegateType"]));
                }
            }

            return delegates;
        }
    }
}
